package com.gitee.xmhzzz.component.mongodb;

import org.bson.types.Decimal128;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.DefaultDbRefResolver;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.mapping.MongoMappingContext;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * @ClassName MongodbConfiguration
 * @Description
 * @Author wzq
 * @Date 2023/8/2 10:50
 * @Version 1.0
 */
@Configuration
public class MongodbConfiguration {
    @Bean
    public MappingMongoConverter mappingMongoConverter(@Autowired MongoDatabaseFactory mongoDatabaseFactory,
                                                       @Autowired MongoMappingContext context) {
        DefaultDbRefResolver dbRefResolver = new DefaultDbRefResolver(mongoDatabaseFactory);
        MappingMongoConverter converter = new MappingMongoConverter(dbRefResolver, context);
        converter.setCustomConversions(new CustomConversions(
                Arrays.asList(new BigDecimalToDecimal128Converter(), new Decimal128ToBigDecimalConverter())));
        return converter;
    }

    @Bean
    public MongoTemplate mongoTemplate(@Autowired MongoDatabaseFactory mongoDatabaseFactory, @Autowired MappingMongoConverter cts) {
        return new MongoTemplate(mongoDatabaseFactory, cts);
    }

    public static class Decimal128ToBigDecimalConverter implements Converter<Decimal128, BigDecimal> {
        @Override
        public BigDecimal convert(Decimal128 s) {
            return s == null ? null : s.bigDecimalValue();
        }

    }

    public static class BigDecimalToDecimal128Converter implements Converter<BigDecimal, Decimal128> {
        @Override
        public Decimal128 convert(BigDecimal s) {
            return s == null ? null : new Decimal128(s);
        }
    }
}
